/*
--------------------------------------------------------------------------------
				Ak-Lib. 
			 Project       	: Ak-Lib
			 Group         	: Ak-Lib R&D Team
			 Author        	: Ocean.Wang
			 Create Date 	: 05-01-2010
--------------------------------------------------------------------------------
Code Name 	:  A.K 	~v~
Description	:  Yet Another Cross-Platform Lib.
Cautions    	:
--------------------------------------------------------------------------------
Change History:
Version		: 0.1
Building 		: 05/01/10
10-05.01 first draft, build, debug and test.
--------------------------------------------------------------------------------
*/
#include "ak_sqlite.h"
#include "sqlite3.h"

void * 	SSqlite_Open(const char * hFile)
{
	sqlite3 * pDb = NULL;
	if(sqlite3_open_v2(hFile, &pDb, SQLITE_OPEN_READONLY| SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX, NULL) != SQLITE_OK){
		return NULL;
	}

	return pDb;
}

int 	SSqlite_Close(void * hDb)
{
	if(hDb && (sqlite3_close((sqlite3 *)hDb) == SQLITE_OK)){
		return 0;
	}
	return -1;
}

/* SQLite Prepare V2 */
int 	SSqlite_Prepare(void * hDb, const char * hSql, void ** ppStmt)
{
	char 	* dummy;
	return sqlite3_prepare_v2((sqlite3 *)hDb, hSql, SYS_STRLEN(hSql), (sqlite3_stmt **)ppStmt, (const char**) &dummy);
}


/*  	If an sqlite3_exec() callback returns non-zero,
** 	the sqlite3_exec() routine returns SQLITE_ABORT 
**	without invoking the callback again and 
**	without running any subsequent SQL statements. 
*/
int 	SSqlite_Exec(void * hDb, _t_sqlite_exec * sExec)
{
	if(hDb && sExec && (sExec->cbFunc)){
		sqlite3_exec((sqlite3 *)hDb, sExec->sql, sExec->cbFunc, sExec->pArg, NULL);
	}
	return -1;
}


/* ---------------------------------------------------------------------------
1. Table : Key/Value
"CREATE TABLE %s (s_key BLOB, s_val BLOB)",
"CREATE INDEX idx_key ON %s (s_key)",

2. Select: 
"SELECT s_val FROM %s WHERE gn_key = ? LIMIT %u",

3. Stmt & While{} Process the Blob.
*/

int 	SSqlite_Blob(void * hDb, _t_sqlite_blob * sBlob)
{
	int 			i, cLen;		/* Column Length */
	void 		 * 	cBlob;
	sqlite3_stmt * 	stmt = NULL;

	if(	hDb && sBlob && (sBlob->cbFunc) &&
		SSqlite_Prepare((sqlite3 *)hDb, sBlob->sql, (void **)(&stmt)) == SQLITE_OK){
		/* Binding the Blob */
		sqlite3_bind_blob(stmt, sBlob->qFid, sBlob->qBlob, sBlob->lBlob, SQLITE_STATIC);
		i = 0;
		while(sqlite3_step(stmt) == SQLITE_ROW)	{
			cLen 	= sqlite3_column_bytes(stmt, sBlob->rFid);
			cBlob 	= (void *) sqlite3_column_blob(stmt, sBlob->rFid);
			sBlob->cbFunc(i, cBlob);
		}

		/* Fini the Stmt */		
		sqlite3_finalize(stmt);
	}

	return 0;
}



